package com.schedule.task.component;

import com.alibaba.fastjson.JSON;
import com.schedule.task.constant.Socket;
import com.schedule.task.util.SocketHeader;
import com.schedule.task.vo.SocketResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WebSocketConnectListener implements ApplicationListener<SessionConnectEvent> {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void onApplicationEvent(SessionConnectEvent event) {
//        log.info("WebSocketConnectedListener:"+event.getMessage());
        //获取Session连接信息
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());

        //用户ID
//        System.out.println(JSON.toJSONString(sha));
        String userId = sha.getFirstNativeHeader(Socket.Prefix.USER_PRE_GET);
//        System.out.println("UserId:" + userId);
        //获取SessionId
        String sessionId = sha.getSessionId();
//        System.out.println("sessionId:" + sessionId);
        if (null != userId) {
            stringRedisTemplate.opsForValue().set(Socket.Prefix.USER_PRE_SET+ userId, sessionId, 60 * 60 * 2, TimeUnit.SECONDS);//过期时间
            stringRedisTemplate.opsForValue().set( sessionId, userId, 60 * 60 * 2, TimeUnit.SECONDS);//过期时间
        }
    }
}
